import { Login } from '@/api/admin.js';
import { UserLogin } from '@/api/user.js';

const state = {
   userInfo: JSON.parse(localStorage.getItem('userInfo') || null) || {},
   token: localStorage.getItem('token') || '',
   imageUrl: 'http://127.0.0.1:9999',
   roleName: localStorage.getItem('roleName') || '' 
}
const mutations = {
   CLEAR_USERINFO: (state) => {
      state.userInfo = ''
      state.token = ''
      state.roleName = ''
      localStorage.clear()
   },

   SET_INFO: (state, data) => {
      state.userInfo = data;
      state.token = data.token;
      localStorage.setItem('userInfo', JSON.stringify(data))
      localStorage.setItem('token', data.token)
   }
}
const actions = {
   login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
         Login(userInfo).then((res) => {
            commit('SET_INFO', res.data)
            state.roleName = userInfo.roleName;
            localStorage.setItem('roleName', userInfo.roleName);
            resolve()
         }).catch((err) => {
            console.log("异常结果", err)
            reject(err)
         })

      })
   },
    userLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
         UserLogin(userInfo).then((res) => {
            commit('SET_INFO', res.data)
            state.roleName = userInfo.roleName;
            localStorage.setItem('roleName', userInfo.roleName);
            resolve()
         }).catch((err) => {
            console.log("异常结果", err)
            reject(err)
         })

      })
   },

   logout({ commit }) {
      commit('CLEAR_USERINFO')
   }
}
export default {
   namespace: true,
   state,
   mutations,
   actions
}